package com.yingside.gui.review;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class MovieDao {

    public List<Movie> list(){
        List<Movie> list = new ArrayList<>();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader("data/movie.txt"));

            String str = null;

            while((str = br.readLine()) != null){
                String [] strs = str.split("\\s+");

                Integer id = Integer.parseInt(strs[0]);
                String movieName = strs[1];
                Double price = Double.parseDouble(strs[2]);
                String director = strs[3];

                Movie m = new Movie(id,movieName,price,director);
                list.add(m);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return list;
    }

    public boolean del(int id){

        boolean flag = false;
        List<Movie> list = list();

        for (int i = 0; i < list.size(); i++) {
            Movie m = list.get(i);
            if(m.getId() == id){
                list.remove(m);
                flag = true;
                break;
            }
        }

        PrintWriter out = null;

        try {
            out = new PrintWriter("data/movie.txt");

            for (int i = 0; i < list.size(); i++) {
                Movie m = list.get(i);
                String s = m.getId() + " " + m.getMovieName() + " " + m.getPrice() + " " + m.getDirector();
                out.println(s);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }

        return flag;

    }
}
